有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用GaussLegendre算法在java中逼近Pi

刚开始学习java,并试图编写一段简单的代码来显示基于Gauss-Legendre algorithm的Pi近似值;我从下面的代码在命令行中得到的结果是-33.343229。。。我觉得这很奇怪。我知道我的代码不完整,因为我对小数点后的位数没有限制,我将尝试使用BigDecimal来获得小数点后的位数。在阅读了文档之后,我不太明白我应该用它做什么

有没有人知道我目前是否可以纠正任何错误,以及如何限制小数点后的位数?谢谢大家!

class calculatePi {
public static void main(String[] args) {
    calculatePi x = new calculatePi();
    double y = x.approxPi(3);       //3 iterations
        System.out.print(y);
}
double approxPi(int i) {
    double a = 1;           //The initial conditions for the iteration
    double b = 1 / Math.sqrt(2);
    double t = 1/4;
    double p = 1;
    double a1 = 0;          //The internal n+1 terms for the iteration
    double b1 = 0;
    double t1 = 0;
    double p1 = 0;
    while (i > 0) {
        a1 = (a + b) / 2;
        b1 = Math.sqrt(a*b);
        t1 = t - p*(a - a1)*(a - a1);
        p1 = 2*p;
        a = a1;
        b = b1;
        t = t1;
        p = p1;
        i = i - 1;
    }
double applepie = ((a + b)*(a + b))/(4*t);
return applepie;
}

}


共 (1) 个答案

  1. # 1 楼答案

    double t = 1/4;1/4进行整数除法,结果为0。试试1/4.0